package kuzmenkov.oip.controller.applet;

import java.util.Locale;
import java.util.logging.Logger;

import org.springframework.context.MessageSource;

/**
 * The class is responsible for a internationalization
 * 
 * @author Michael Kuzmenkov
 * 
 */
public class I18nTool {
	private Logger log = Logger.getLogger(I18nTool.class.getName());
	/**
	 * A service of a remote access to a server
	 */
	private ClientService service;
	/**
	 * A spring object which reads i18n messages from property files
	 */
	private MessageSource messageSource;

	private static I18nTool instance = new I18nTool();

	public static I18nTool getInstance() {
		return instance;
	}

	public static void init(ClientService service) {
		getInstance().setClientService(service);
	}

	/**
	 * Constructor is private because of a singleton
	 */
	private I18nTool() {
	}

	public void setClientService(ClientService service) {
		this.service = service;
		this.messageSource = service.getMessageSource();
	}

	/**
	 * 
	 * @param key
	 *            a key into a properties file
	 * @return i18n message
	 */
	public String getMessage(String key) {
		return getMessage(key, null);
	}

	/**
	 * Returns a message from i18n resource files
	 * 
	 * @param key
	 * @return
	 */
	public String getMessage(String key, Object[] args) {
		Locale locale = getLocale();
		return messageSource.getMessage(key, args, locale);
	}

	/**
	 * Returns a current locale of a external site
	 * 
	 * @return a current locale
	 */
	public Locale getLocale() {
		Locale locale = null;
		try {
			locale = service.getRemoteLocale();
		} catch (Exception e) {
			e.printStackTrace();
			log.warning("While getting of a remote locale an error occurred. "
					+ "A locale of a VM will be used");
			locale = Locale.getDefault();
		}
		return locale;
	}

}
